<template>
  <div class="loginMain">
    <img class="logo" alt="logo_float" src="@/assets/logo_login2.png" />
    <div class="form_wrap">
      <div class="left formLeftImageWrap">
        <img src="@/assets/loginimg.png" alt="" class="formLeftImage" />
      </div>
      <div class="right formWrap">
        <div class="pk__modelogin_cut" @click="onPkModeloginCut">
          <div v-if="!pkLoginModeType" class="pk__mode__container">
            <img class="icon" src="@/assets/pk_login1.png" alt="" />
            <!-- <span class="title">切换岗亭<br />监控端</span> -->
          </div>
          <div v-else class="pk__mode__container">
            <img class="icon" src="@/assets/pk_login2.png" alt="" />
            <!-- <span class="title">切换场端</span> -->
          </div>
        </div>

        <a-form :form="form" ref="formLogin" id="formLogin" class="formLogin">
          <div class="form_header">
            欢迎登录<span>{{ !pkLoginModeType ? '车场' : '岗亭监控' }}管理端</span>
          </div>
          <div class="username_password_login">用户名密码登录</div>
          <a-form-item style="height: 3rem">
            <a-input
              v-decorator="['username', validatorRules.username]"
              type="text"
              class="username"
              placeholder="用户名"
              @blur="getParkWorkStationList"
            >
              <a-icon class="user-icon" slot="prefix" type="user" :style="{ color: 'rgba(66, 122, 238, 1)' }" />
            </a-input>
          </a-form-item>

          <a-form-item style="height: 3rem" v-if="pkLoginModeType">
            <div class="ant-col ant-form-item-control-wrapper">
              <div class="ant-form-item-control">
                <span class="ant-form-item-children"
                  ><span class="ant-input-affix-wrapper"
                    ><span class="ant-input-prefix"
                      ><i aria-label="图标: desktop" class="anticon anticon-desktop" style="color: rgb(66, 122, 238)"
                        ><svg
                          viewBox="64 64 896 896"
                          data-icon="desktop"
                          width="1em"
                          height="1em"
                          fill="currentColor"
                          aria-hidden="true"
                          focusable="false"
                          class=""
                        >
                          <path
                            d="M928 140H96c-17.7 0-32 14.3-32 32v496c0 17.7 14.3 32 32 32h380v112H304c-8.8 0-16 7.2-16 16v48c0 4.4 3.6 8 8 8h432c4.4 0 8-3.6 8-8v-48c0-8.8-7.2-16-16-16H548V700h380c17.7 0 32-14.3 32-32V172c0-17.7-14.3-32-32-32zm-40 488H136V212h752v416z"
                          ></path></svg></i
                    ></span>
                    <!-- <input type="text" class="ant-input" /> -->
                    <a-select
                      v-decorator="['province', { rules: [{ required: true, message: '请选择工作站' }] }]"
                      placeholder="选择工作站"
                      :options="ParkWorkStationList"
                    >
                    </a-select> </span></span
                ><!---->
              </div>
            </div>
          </a-form-item>

          <a-form-item style="height: 3rem">
            <a-input
              v-decorator="['password', validatorRules.password]"
              type="password"
              class="password"
              autocomplete="false"
              placeholder="密码"
            >
              <a-icon slot="prefix" type="lock" :style="{ color: 'rgba(66, 122, 238, 1)' }" />
            </a-input>
          </a-form-item>

          <a-form-item class="checkboxItem">
            <a-checkbox v-model="formLogin.rememberMe">自动登录</a-checkbox>
          </a-form-item>

          <a-form-item>
            <a-button
              type="primary"
              htmlType="submit"
              class="login_button"
              :loading="loginBtn"
              @click.stop.prevent="handleSubmit"
              :disabled="loginBtn"
              >登录
            </a-button>
          </a-form-item>
          <div class="foot">Copyright © 金豆豆互联网有限责任公司技术支持  场端管理系统v3.0.1.0</div>
        </a-form>
      </div>
    </div>
  </div>
</template>

<script>
import TwoStepCaptcha from '@/components/tools/TwoStepCaptcha'
import { mapActions } from 'vuex'
import { timeFix, isEmpty, filterObj, cloneObject } from '@/utils/util'
import Vue from 'vue'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import JGraphicCode from '@/components/jeecg/JGraphicCode'
import { encryption, getEncryptedString } from '@/utils/encryption/aesEncrypt'
import { getAction, httpAction, postAction, putAction } from '@/api/manage'
export default {
  components: {
    TwoStepCaptcha,
    JGraphicCode,
  },
  data() {
    return {
      src: 'https://cube.elemecdn.com/6/94/4d3ea53c084bad6931a56d5158a48jpeg.jpeg',
      customActiveKey: 'tab1',
      loginBtn: false,
      // login type: 0 email, 1 username, 2 telephone
      loginType: 0,
      requiredTwoStepCaptcha: false,
      stepCaptchaVisible: false,
      form: this.$form.createForm(this),
      encryptedString: {
        key: '',
        iv: '',
      },
      state: {
        time: 60,
        smsSendBtn: false,
      },
      formLogin: {
        username: '',
        password: '',
        captcha: '',
        mobile: '',
        rememberMe: true,
      },
      validatorRules: {
        username: {
          rules: [
            {
              required: true,
              message: '请输入用户名!',
            },
            {
              validator: this.handleUsernameOrEmail,
            },
          ],
        },
        password: {
          rules: [
            {
              required: true,
              message: '请输入密码!',
              validator: 'click',
            },
          ],
        },
        mobile: {
          rules: [
            {
              validator: this.validateMobile,
            },
          ],
        },
        captcha: {
          rule: [
            {
              required: true,
              message: '请输入验证码!',
            },
          ],
        },
      },
      verifiedCode: '',
      departList: [],
      departVisible: false,
      departSelected: '',
      currentUsername: '',
      validate_status: '',
      captchaSrc: '',
      verifiedCodess: '',
      selectedWorkStation: '', // 选择工作站
      province: undefined,
      pkLoginModeType: true, // true岗亭端 false场端
      ParkWorkStationList: Array(),
    }
  },
  created() {
    Vue.ls.remove(ACCESS_TOKEN)
    this.getRouterData()
    this.getEncrypte()
    this.pkLoginModeType = Vue.ls.get('Watchhouse')
  },
  methods: {
    // 工作站登录
    bindWorkStation() {
      let userInfo = Vue.ls.get('Login_Userinfo')
      postAction('/parking/parkWorkStation/bindWorkStation', {
        id: this.selectedWorkStation,
        operationName: userInfo.username,
        realName: userInfo.realname
      }).then((ret) => {
        if (ret.success) {
          Vue.ls.set('WORKID', this.selectedWorkStation)
          this.loginSuccess()
          return
        }
        this.loginBtn = false
      })
    },
    //将本机mac保存到storage中
    saveMacToStorage() {
      return new Promise((resolve) => {
        let LODOP = window.getLodop()
        LODOP.GET_SYSTEM_INFO('NetworkAdapter.1.PhysicalAddress')
        if (LODOP.CVERSION) {
          window.CLODOP.On_Return = function (TaskID, Value) {
            Vue.ls.set('mac', Value)
            resolve()
          }
        }
      })
    },
    // 获取工作站列表
    getParkWorkStationList() {
      let username = this.form.getFieldValue('username')
      getAction('/sentryBox/getParkWorkStationList', { username }).then((res) => {
        if (isEmpty(res.result)) return // 未查询到工作站

        let i = 0,
          ParkWorkStationList = Array()
        while (res.result.length > i) {
          !isEmpty(res.result[i]) &&
            ParkWorkStationList.push({
              value: res.result[i].id,
              label: res.result[i].workName,
            })
          i++
        }
        this.ParkWorkStationList = ParkWorkStationList
      })
    },
    // 更换登录方式
    onPkModeloginCut() {
      this.province = undefined
      this.pkLoginModeType = !this.pkLoginModeType
      Vue.ls.set('Watchhouse', this.pkLoginModeType) // 是否车场岗亭端.
    },

    handleSubmit() {
      let that = this
      let loginParams = {
        remember_me: that.formLogin.rememberMe,
      }
      that.loginBtn = true
      // 使用账户密码登陆

      that.form.validateFields(
        ['username', 'password', 'province'],
        {
          force: true,
        },
        (err, values) => {
          if (!err) {
            let { province } = values
            province && (this.selectedWorkStation = province)
            loginParams.username = values.username
            // loginParams.password = values.password
            let encryptStr = encryption(values.password, that.encryptedString.key, that.encryptedString.iv)
            loginParams.password = encodeURI(encryptStr)
            that
              .Login(loginParams)
              .then(() => {
                // this.departConfirm(res)

                if (isEmpty(province)) {
                  this.loginSuccess()
                  return
                }

                this.bindWorkStation()
              })
              .catch((err) => {
                that.requestFailed(err)
              })
          } else {
            that.loginBtn = false
          }
        }
      )
    },
    // 登录成功
    loginSuccess() {
      let tonane = 'dashboard'
      this.loginBtn = false
      if (this.province) {
        console.log('跳转岗亭监控')
        tonane = 'Watchhouse'
      }
      this.$router.push({
        name: tonane,
      })
      this.$notification.success({
        message: '欢迎',
        description: `${timeFix()}，欢迎回来`,
      })
    },
    ...mapActions(['Login', 'Logout', 'PhoneLogin']),
    // handler
    handleUsernameOrEmail(rule, value, callback) {
      const regex = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/
      if (regex.test(value)) {
        this.loginType = 0
      } else {
        this.loginType = 1
      }
      callback()
    },
    handleTabClick(key) {
      this.customActiveKey = key
      // this.form.resetFields()
    },

    stepCaptchaSuccess() {
      this.loginSuccess()
    },
    stepCaptchaCancel() {
      this.Logout().then(() => {
        this.loginBtn = false
        this.stepCaptchaVisible = false
      })
    },
    cmsFailed(err) {
      this.$notification['error']({
        message: '登录失败',
        description: err,
        duration: 4,
      })
    },
    requestFailed(err) {
      this.$notification['error']({
        message: '登录失败',
        description: ((err.response || {}).data || {}).message || err.message || '请求出现错误，请稍后再试',
        duration: 4,
      })
      this.loginBtn = false
    },
    validateMobile(rule, value, callback) {
      if (!value || new RegExp(/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/).test(value)) {
        callback()
      } else {
        callback('您的手机号码格式不正确!')
      }
    },
    departConfirm(res) {
      if (res.success) {
        let multi_depart = res.result.multi_depart
        //0:无部门 1:一个部门 2:多个部门
        if (multi_depart == 0) {
          this.loginSuccess()
          // this.$notification.warn({
          //   message: '提示',
          //   description: `您尚未归属部门,请确认账号信息`,
          //   duration:3
          // });
        } else if (multi_depart == 2) {
          this.departVisible = true
          this.currentUsername = this.form.getFieldValue('username')
          this.departList = res.result.departs
        } else {
          this.loginSuccess()
        }
      } else {
        this.requestFailed(res)
        this.Logout()
      }
    },
    departClear() {
      this.departList = []
      this.departSelected = ''
      this.currentUsername = ''
      this.departVisible = false
      this.validate_status = ''
    },
    departChange(value) {
      this.validate_status = 'success'
      this.departSelected = value
    },
    getRouterData() {
      this.$nextTick(() => {
        this.form.setFieldsValue({
          username: this.$route.params.username,
        })
      })
    },
    //强制获取密码加密规则
    getEncrypte() {
      getEncryptedString().then((data) => {
        this.encryptedString = data
      })
    },
  },
}
</script>

<style scoped>
html {
  font-size: 20px;
  min-width: 1080px;
  min-height: 969px;
}

@media screen and (max-width: 1680px) {
  html {
    font-size: 16px;
  }
}

@media screen and (max-width: 1440px) {
  html {
    font-size: 14px;
  }
}

@media screen and (max-width: 1080px) {
  html {
    font-size: 12px;
  }
}

@media screen and (max-width: 960px) {
  html {
    font-size: 10px;
  }
}

@media screen and (max-width: 768px) {
  html {
    font-size: 8px;
  }
}

.loginMain {
  display: flex;
  font-family: MicrosoftYaHei;
  width: 100%;
  height: 100%;
  background: url('~@/assets/loginbg@3x.png') no-repeat center center;
  background-size: 100% 100%;
  justify-content: center;
  align-items: center;
  position: relative;
}
.loginMain .form_wrap {
  /* width: calc(100% - 34rem);
  height: calc(100% - 16rem); */
  width: 62.5%;
  height: 72%;
  border-radius: 1.5rem;
  background-color: #fff;
  display: flex;
  justify-content: center;
  align-content: center;
}
.loginMain .form_wrap .left,
.loginMain .form_wrap .right {
  width: 50%;
  height: 100%;
  position: relative;
}
.formLeftImageWrap {
  justify-content: center;
  align-items: center;
  display: flex;
}

.loginMain .formLeftImage {
  width: 72%;
  height: 72%;
}

.loginMain .logo {
  left: 3rem;
  top: 2.5rem;
  width: 8rem;
  height: 2.5rem;
  position: absolute;
}

.loginMain .formLogin {
  position: absolute;
  width: 23rem;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.formLogin .ant-form-item {
  margin-bottom: 1rem;
}

.formLogin .ant-form-item-control {
  line-height: 2rem;
}
.formLogin .checkboxItem .ant-form-item-control {
  line-height: normal;
}

.loginMain .form_header {
  font-size: 1.4rem;
  color: #1f1f1f;
  letter-spacing: 0.1rem;
  line-height: 2.5rem;
}
.loginMain .form_header span {
  color: #427aee;
}

.loginMain .codeImg {
  display: block;
  margin: auto;
  height: 3rem;
  width: 96%;
  border-radius: 4px;
}

.username_password_login {
  line-height: 1.3rem;
  font-size: 1rem;
  color: #427aee;
  margin: 1.8rem 0 1rem;
}

.login_button {
  width: 100%;
  height: 3rem;
  background: #427aee;
  border-radius: 4px;
  font-size: 0.9rem;
  letter-spacing: 0.5rem;
}
.loginMain .foot {
  font-size: 0.6rem;
  color: #333333;
  letter-spacing: 1px;
  text-align: center;
  text-align: center;
}
.loginMain .formWrap {
  position: relative;
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  margin-top: 1.9rem;
}
.pk__modelogin_cut {
  text-align: center;
  position: absolute;
  top: calc(-1.9rem);
  right: 0;
  border-top-right-radius: 1.5rem;
  border-bottom-left-radius: 1.5rem;
  background: #f7f7f7;
  /* padding: 0.42rem 0.8rem 0.55rem; */
  font-family: MicrosoftYaHei;
  width: 18%;
  height: 16%;
  color: #333333;
  display: flex;
  align-items: center;
}
.pk__mode__container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}
.pk__mode__container .title {
}
.pk__mode__container .icon {
  width: 100%;
  height: 100%;
}
</style>

<style>
.loginMain .formLogin .ant-input {
  font-size: 0.8rem;
  line-height: 1rem;
  padding-top: 1rem;
  padding-bottom: 1rem;
  height: 3rem;
  background-color: #f9f9fa;
  border: none;
}
.loginMain .formLogin .ant-select-selection--single {
  font-size: 0.8rem;
  height: 3rem;
  background-color: #f9f9fa;
  border: none;
}
.loginMain .formLogin .ant-select-selection-selected-value {
  line-height: 3rem;
  margin-left: 1.2rem;
}
.loginMain .formLogin .ant-select-selection__placeholder {
  margin-left: 1.2rem;
}
.loginMain .formLogin .ant-select-selection__rendered {
  line-height: 3rem;
}
</style>
